package com.game;

import java.util.LinkedList;

public class Snake {
    private LinkedList<Node> body;
    private Direction direction = Direction.RIGHT;
    private boolean isLiving = true;

    public Direction getDirection() {
        return direction;
    }

    public void setDirection(Direction direction) {
        this.direction = direction;
    }

    public Snake() {
        initSnake();
    }

    private void initSnake() {
        body = new LinkedList();
        body.add(new Node(10, 20));
        body.add(new Node(9, 20));
        body.add(new Node(8, 20));
        body.add(new Node(7, 20));
        body.add(new Node(6, 20));
        body.add(new Node(5, 20));

    }

    public void move() {
        Node head = body.getFirst();

        /**
         * 用linkedList的头元素变动，删除尾元素
         */
        //判断是否活着
        if (isLiving) {
            switch (direction) {
                case UP:
                    body.addFirst(new Node(head.getX(), head.getY() - 1));
                    break;
                case DOWN:
                    body.addFirst(new Node(head.getX(), head.getY() + 1));
                    break;
                case LEFT:
                    body.addFirst(new Node(head.getX() - 1, head.getY()));
                    break;
                case RIGHT:
                    body.addFirst(new Node(head.getX() + 1, head.getY()));
                    break;
            }
            body.removeLast();

            //撞墙
            head = body.getFirst();
            if (head.getX() < 0 || head.getY() < 0 || head.getX() >= 40 || head.getY() >= 40) {
                isLiving = false;
            }

            //撞自己  头除外
            for (int i = 1; i < body.size(); i++) {
                Node node = body.get(i);
                if (head.getX() == node.getX() && head.getY() == node.getY()) {
                    isLiving = false;
                }
            }


        }


    }

    public LinkedList<Node> getBody() {
        return body;
    }

    public void setBody(LinkedList<Node> body) {
        this.body = body;
    }

    public void eat() {
        Node head = body.getFirst();
        switch (direction) {
            case UP:
                body.addFirst(new Node(head.getX(), head.getY() - 1));
                break;
            case DOWN:
                body.addFirst(new Node(head.getX(), head.getY() + 1));
                break;
            case LEFT:
                body.addFirst(new Node(head.getX() - 1, head.getY()));
                break;
            case RIGHT:
                body.addFirst(new Node(head.getX() + 1, head.getY()));
                break;
        }
    }
}
